package com.weasel.http;

import com.weasel.http.handler.DownloadHandler;
import com.weasel.http.handler.UploadHandler;
import com.weasel.http.helper.HttpStatusHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;


/**
 * @author Dylan
 * @time 2015年9月24日
 */
public final class SimpleHttpUploadAndDownloadSecretary {


	/**
	 * @param uri
	 * @param files
	 * @param handler
	 * @param <T>
	 * @return
	 */
	public static <T> T upload(String uri,File[] files,UploadHandler<T> handler){
		
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create()
															   .setCharset(Consts.UTF_8)
															   .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		for(File file : files){
			builder.addBinaryBody(StringUtils.substringBefore(file.getName(), "."), file);
		}

		HttpEntity entity =	builder.build();
		
		CloseableHttpResponse response = HttpClientSecretary.post()
				                                            .addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString())
															.withURI(uri)
										    		        .withEntity(entity)
										    		        .doIt();
		T t = null;
		if(null != handler){
			t = handler.handler(response);
		}
		
		HttpClientSecretary.release(response);
		return t;
	}
	
	
	
	/**
	 * @param uri
	 * @param handler
	 * @throws UnsupportedOperationException
	 * @throws IOException
	 */
	public static <T> T download(String uri,DownloadHandler<T> handler) throws UnsupportedOperationException, IOException{
		
		
		CloseableHttpResponse response = HttpClientSecretary.get()
													        .withURI(uri)
													        .doIt();
		
		T t = null;
		if(HttpStatusHelper.isOK(response.getStatusLine().getStatusCode())){
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			if(null != handler){
				t = handler.handler(response,is);
			}
			is.close();
		}
		
		HttpClientSecretary.release(response);
		return t;
	}


}
